//
//  RMThirdViewController.m
//  rmplanner
//
//  Created by Andrew Pigram on 4/05/12.
//  Copyright (c) 2012 PiAMP Productions. All rights reserved.
//

#import "RMThirdViewController.h"
#import "RMTabBarController.h"
#import <QuartzCore/QuartzCore.h>

@interface RMThirdViewController ()

- (void)dismiss;

@end

@implementation RMThirdViewController

@synthesize detailView, retData;

#pragma mark UIViewController functions

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
	
	self.navigationItem.title = @"Feedback";
	
	[[detailView layer] setBorderColor:[[UIColor grayColor] CGColor]];
	[[detailView layer] setBorderWidth:1.0];
	[[detailView layer] setCornerRadius:5.0];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
	if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
		return (interfaceOrientation == UIInterfaceOrientationPortrait);
	else
		return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}

#pragma mark Interface Builder selectors

// process a feedback submission. Use the segment control to determine the type of feedback.
- (IBAction)submit
{
	// dismiss the keyboard
	[detailView resignFirstResponder];
	
	// send the feedback to the server
	NSURL* url = [[NSURL alloc] initWithScheme:@"http" host:@"rmplanner.net" path:@"/kitchen/scripts/feedback"];
	NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];
	[request setHTTPMethod:@"POST"];
	NSData* data = [[NSString stringWithFormat:@"content=%@&id=%d", detailView.text, [[NSUserDefaults standardUserDefaults] integerForKey:@"uid"]] dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
	[request setHTTPBody:data];
	
	NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	
	NSAssert((connection != nil), @"Could not connect");
	
}

- (IBAction)logout
{
	[self dismissModalViewControllerAnimated:YES];
}

#pragma mark NSURLConnection delegate functions

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
	// initialise the data container
	retData = [NSMutableData data];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	// append the newly downloaded data
	[retData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	// nullify the connection and turn off the activity indicator
	connection = nil;
	
	// display an alert confirming that the feedback was submitted
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	 UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Feedback" message:[[NSString alloc] initWithData:retData encoding:NSUTF8StringEncoding] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
	[alertView show];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	NSLog(@"%@", [error description]);
	connection = nil;
	UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Connection Error" message:@"Connection to server failed. Your feedback has not been submitted." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
	[alertView show];
}

#pragma mark UITextViewDelegate methods

- (void)textViewDidBeginEditing:(UITextView *)textView
{
	if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
	{
		UIBarButtonItem* button = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(dismiss)];
		self.tabBarController.navigationItem.leftBarButtonItem = button;
	}
	textView.text = @"";
}

- (void)dismiss
{
	[detailView resignFirstResponder];
	self.tabBarController.navigationItem.leftBarButtonItem = nil;
}

@end
